package com.ziqikeji.xianyan.controller.user;

import com.ziqikeji.xianyan.common.DatagridDTO;
import com.ziqikeji.xianyan.dto.user.RoleDTO;
import com.ziqikeji.xianyan.dto.user.UserDTO;
import com.ziqikeji.xianyan.entity.user.User;
import com.ziqikeji.xianyan.service.user.RoleService;
import com.ziqikeji.xianyan.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户
 *
 * @author liuyu
 */
@Controller
@RequestMapping("admin/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String hello() {
        return "/admin/user/listAll";
    }

    /**
     * 获取列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAll")
    public DatagridDTO datagrid() {
        List<UserDTO> users = new ArrayList<>();
        List<User> userList = this.userService.getAllByDeleteFlag();
        for (User user : userList) {
            UserDTO userDTO = new UserDTO(user);
            users.add(userDTO);
        }
        return new DatagridDTO("列表获取成功", 0, users.size(), users);
    }

    /**
     * 获取列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "datagrid")
    public DatagridDTO getPage(@RequestParam(value = "pageNumber", defaultValue = "1") String pageNumber,
                               @RequestParam(value = "pageSize", defaultValue = "10") String pageSize) {
        Page pageImpl = null;
        try {
            int page = 0;
            int size = 10;
            if (!StringUtils.isEmpty(pageNumber)) {
                page = Integer.parseInt(pageNumber) - 1;
                page = page < 0 ? 0 : page;
            }
            if (!StringUtils.isEmpty(pageSize)) {
                size = Integer.parseInt(pageSize);
                size = size < 0 ? 0 : size;
            }
            Page<User> userPage = this.userService.getPage(page, size);

            List<UserDTO> users = new ArrayList<>();
            for (User user : userPage.getContent()) {
                UserDTO userDTO = new UserDTO(user);
                users.add(userDTO);
            }
            PageRequest pageRequest = PageRequest.of(page, size);
            pageImpl = new PageImpl<>(users, pageRequest, userPage.getTotalElements());
        } catch (Exception e) {
            return new DatagridDTO("获取失败(错误信息：" + e.getMessage() + "）", 1, new ArrayList());
        }
        return new DatagridDTO("列表获取成功", 0, pageImpl.getTotalElements(), pageImpl.getContent());
    }

    @RequestMapping("/add")
    public String add(Model model) {
        User user = new User();
        model.addAttribute("user", user);

        List<RoleDTO> roleDTOList = this.roleService.getAllRoleDTOList();
        model.addAttribute("roleDTOList", roleDTOList);

        model.addAttribute("action", "save");
        return "admin/user/edit";
    }

    /**
     * 通过ID获取用户
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "get/{id}", method = RequestMethod.GET)
    public User get(@PathVariable("id") String id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return this.userService.get(id);
    }


    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ResponseEntity save(@ModelAttribute User user) {
        try {
            //增加用户权限
            user = this.userService.setRoleByRoleId(user.getRoleIdStr(), user);
            this.userService.save(user);
        } catch (Exception e) {
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 进入修改页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "modify/{id}", method = RequestMethod.GET)
    public String modify(@PathVariable("id") String id, Model model) {
        User user = userService.get(id);
        model.addAttribute("user", user);

        List<RoleDTO> roleDTOList = this.roleService.getAllRoleDTOList();
        model.addAttribute("roleDTOList", roleDTOList);

        model.addAttribute("action", "update");
        return "admin/user/edit";
    }

    /**
     * 修改更新用户
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ResponseEntity update(@ModelAttribute User user) {
        try {

            //清除原有的权限关联 TODO 显示中不是这样使用的，但是没有找到合适的方法，先暂时用这种方式实现修改
            User user1 = this.userService.get(user.getId());
            user1.setRoleList(new ArrayList<>());
            user1.setRoleIdStr(null);
            this.userService.update(user1);

            //增加用户权限
            user = this.userService.setRoleByRoleId(user.getRoleIdStr(), user);
            this.userService.update(user);
        } catch (Exception e) {
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 进入修改页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
    public String view(@PathVariable("id") String id, Model model) {
        User user = userService.get(id);
        model.addAttribute("user", user);
        return "admin/user/detail";
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
    public ResponseEntity delete(@PathVariable("id") String id) {
        try {
            this.userService.deleteMark(id);
        } catch (Exception e) {
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Organize对象,再把Form提交的内容绑定到该对象上。
     * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
     */
    @ModelAttribute
    public void get(@RequestParam(value = "user.id", defaultValue = "-1") String id, Model model) {
        if (!"-1".equals(id)) {
            User user = this.userService.get(id);
            model.addAttribute("user", user);
        }
    }
}
